<?php
/* SVN FILE: $Id: user.php 19 2007-09-09 23:32:26Z joe.vasquez $ */
/**
 * user model
 * @filesource
 * @author			Joe Vasquez <joe.vasquez@gmail.com>
 * @copyright		Copyright (c) 2007, Joe Vasquez
 * @package			redlettr
 * @subpackage		users
 * @since			0.1A
 * @version			0.1A  $Rev: 19 $
 * @lastmodified	$Date: 2007-09-09 23:32:26 +0000 (Sun, 09 Sep 2007) $
 * @license			http://www.gnu.org/licenses/gpl.html GNU General Public License
 */
 
class User extends AppModel {

	var $name = 'User';
	var $validate = array(
		'email' => array(
			'isEmail'	=> VALID_EMAIL,
			'required'	=> VALID_NOT_EMPTY
		),
		'status'=> array('rule'	=> array('custom','/^active|locked|reset$/'))
	);
	var $actsAs = array('Acl'=>'requester');
	var $maxTries = 3;
	var $searchFields	= array(
		'email'			=> 'email',
		'status'		=> 'status',
		'tries'			=> 'tries',
		'created'		=> 'created',
		'modified'		=> 'modified',
		'displayname'	=> 'Profile.displayname',
		'signature'		=> 'Profile.signature'
	);	

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $hasOne = array(
			'Profile' => array('className' => 'Profile',
								'foreignKey' => 'user_id',
								'fields' => array('displayname','signature'),
								'dependent' => true,
								'autoSave'	=> true
			)
	);

	var $hasAndBelongsToMany = array(
			'Group' => array('className' => 'Group',
						'joinTable' => 'groups_users',
						'foreignKey' => 'user_id',
						'associationForeignKey' => 'group_id',
						'conditions' => '',
						'fields' => '',
						'order' => '',
						'limit' => '',
						'offset' => '',
						'unique' => '',
						'finderQuery' => '',
						'deleteQuery' => '',
						'insertQuery' => ''),
	);

/**
 * required to cascade saves on autoSave == true
 */	
	function afterSave()
	{
		foreach ($this->hasOne as $assoc=>$params)
		{	
		    if ($this->hasOne[$assoc]['autoSave'] === true && !empty ($this->data[$assoc]))
		    {	
		        $this->data[$assoc][$this->hasOne[$assoc]['foreignKey']] = $this->id;
		        $this->{$assoc}->create ();
		        $this->{$assoc}->save($this->data);
		    }
		}
	}

/**
 * @return array user account status options based on enum from mysql table
 */
	function getStatusOptions()
	{
		return array(
			'active'	=> 'active',
			'locked'	=> 'locked',
			'reset'		=> 'reset'
		);
	}

/**
 * increment failed login attempts
 * @param mixed user integer user id or string email
 * @return bool true if tries incremented
 */	
	function incrementTries($user=null)
	{
		if(isset($user))
		{
			if(preg_match('/^[0-9]+$/',$user) != 0)
			{
				$this->id = $user;
			} else {
				$user = $this->findByEmail($user,array('id','tries'));
				if(!empty($user))
				{
					$this->id = $user['User']['id'];
					return $this->saveField('tries',intval($user['User']['tries'])+1);
				} else {
					return false;
				}
			}
		}
		$tries = $this->field('tries');
		return $this->saveField('tries',intval($tries)+1);
	}

/**
 * resets failed login attempts
 * @param mixed user integer user id or string email
 * @return bool true if login attempts reset to zero
 */	
	function resetTries($user=null)
	{
		if(isset($user))
		{
			if(preg_match('/^[0-9]+$/',$user) != 0)
			{
				$this->id = $user;
			} else {
				$user = $this->findByEmail($user,array('id'));
				if(!empty($user))
				{
					$this->id = $user['User']['id'];
					return $this->saveField('tries','0');
				}
			}
		}
		return $this->saveField('tries','0');		
	}

/**
 * check to see if user exits from an email address
 * @param string email
 * @return bool true if user exists
 */	
	function checkForUser($email)
	{
		return ($this->findCount(array('email' => $email)) == 1);
	}
	
    function login($data)
    {
        $user = $this->find(
        	array(
				'email' 	=> $data['email'],
				'password'	=> Security::hash($data['password'])
			),
			array('id','email','status')
		);
        if(!empty($user))
        {
            $this->id = $user['User']['id'];
            $this->resetTries();
            return $user['User'];
        }
        return false;
    }
}
?>